package com.itheima.note.utils;

import com.itheima.common.redis.CacheService;
import com.itheima.model.note.pojos.Note;
import com.itheima.model.user.pojos.User;
import com.itheima.utils.thread.MpThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 笔记统计数据工具类
 * 用于从Redis获取笔记的点赞、收藏等统计数据
 */
@Component
@Slf4j
public class NoteStatisticsUtil {

    @Autowired
    private CacheService cacheService;

    // Redis key常量，与behavior-service保持一致
    private static final String USER_LIKE_KEY = "user_like:%s";
    private static final String USER_COLLECT_KEY = "user_collect:%s";
    private static final String LIKE_COUNT_KEY = "like_count";
    private static final String COLLECT_COUNT_KEY = "collect_count";

    /**
     * 为单个笔记设置统计数据
     *
     * @param note 笔记对象
     */
    public void setNoteStatistics(Note note) {
        if (note == null || note.getId() == null) {
            return;
        }

        try {
            String noteId = note.getId();
            String targetKey = "note:" + noteId;

            // 获取点赞数
            Integer likeCount = getCount(LIKE_COUNT_KEY, targetKey);
            note.setLikeCount(likeCount);

            // 获取收藏数
            Integer collectCount = getCount(COLLECT_COUNT_KEY, targetKey);
            note.setCollectCount(collectCount);

            // 获取当前用户是否点赞/收藏
            User user = MpThreadLocalUtil.getUser();
            if (user != null) {
                note.setIsLiked(isLiked(user.getId(), noteId));
                note.setIsCollected(isCollected(user.getId(), noteId));
            } else {
                note.setIsLiked(false);
                note.setIsCollected(false);
            }

            // TODO: 评论数和分享数暂时设置为0，后续可以从其他服务获取
            note.setCommentCount(0);
            note.setShareCount(0);

        } catch (Exception e) {
            log.error("设置笔记统计数据失败, noteId: {}", note.getId(), e);
            // 设置默认值，避免返回null
            setDefaultStatistics(note);
        }
    }

    /**
     * 批量为笔记列表设置统计数据（性能优化版本）
     *
     * @param notes 笔记列表
     */
    public void batchSetNoteStatistics(List<Note> notes) {
        if (notes == null || notes.isEmpty()) {
            return;
        }

        try {
            // 获取当前用户
            User user = MpThreadLocalUtil.getUser();
            Integer userId = user != null ? user.getId() : null;

            // 批量获取点赞数和收藏数
            Map<String, Integer> likeCountMap = batchGetCounts(notes, LIKE_COUNT_KEY);
            Map<String, Integer> collectCountMap = batchGetCounts(notes, COLLECT_COUNT_KEY);

            // 批量获取用户的点赞和收藏状态
            Map<String, Boolean> likedMap = userId != null ? batchGetUserStatus(notes, userId, USER_LIKE_KEY) : null;
            Map<String, Boolean> collectedMap = userId != null ? batchGetUserStatus(notes, userId, USER_COLLECT_KEY) : null;

            // 为每个笔记设置统计数据
            for (Note note : notes) {
                if (note == null || note.getId() == null) {
                    continue;
                }

                String noteId = note.getId();
                String targetKey = "note:" + noteId;

                // 设置点赞数和收藏数
                note.setLikeCount(likeCountMap.getOrDefault(targetKey, 0));
                note.setCollectCount(collectCountMap.getOrDefault(targetKey, 0));

                // 设置用户点赞和收藏状态
                if (userId != null) {
                    note.setIsLiked(likedMap.getOrDefault(targetKey, false));
                    note.setIsCollected(collectedMap.getOrDefault(targetKey, false));
                } else {
                    note.setIsLiked(false);
                    note.setIsCollected(false);
                }

                // TODO: 评论数和分享数暂时设置为0
                note.setCommentCount(0);
                note.setShareCount(0);
            }

        } catch (Exception e) {
            log.error("批量设置笔记统计数据失败", e);
            // 出错时为所有笔记设置默认值
            notes.forEach(this::setDefaultStatistics);
        }
    }

    /**
     * 批量获取计数数据
     *
     * @param notes    笔记列表
     * @param countKey Redis hash key
     * @return noteId -> count的映射
     */
    private Map<String, Integer> batchGetCounts(List<Note> notes, String countKey) {
        return notes.stream()
                .filter(note -> note != null && note.getId() != null)
                .collect(Collectors.toMap(
                        note -> "note:" + note.getId(),
                        note -> getCount(countKey, "note:" + note.getId()),
                        (v1, v2) -> v1
                ));
    }

    /**
     * 批量获取用户状态（点赞或收藏）
     *
     * @param notes   笔记列表
     * @param userId  用户ID
     * @param userKey 用户状态key模板
     * @return noteId -> status的映射
     */
    private Map<String, Boolean> batchGetUserStatus(List<Note> notes, Integer userId, String userKey) {
        String key = String.format(userKey, userId);
        return notes.stream()
                .filter(note -> note != null && note.getId() != null)
                .collect(Collectors.toMap(
                        note -> "note:" + note.getId(),
                        note -> cacheService.hExists(key, "note:" + note.getId()),
                        (v1, v2) -> v1
                ));
    }

    /**
     * 从Redis获取计数
     *
     * @param countKey  计数key
     * @param targetKey 目标key
     * @return 计数值
     */
    private Integer getCount(String countKey, String targetKey) {
        try {
            Object count = cacheService.hGet(countKey, targetKey);
            if (count != null) {
                return Integer.parseInt(count.toString());
            }
        } catch (Exception e) {
            log.warn("获取计数失败, countKey: {}, targetKey: {}", countKey, targetKey, e);
        }
        return 0;
    }

    /**
     * 判断用户是否点赞
     *
     * @param userId 用户ID
     * @param noteId 笔记ID
     * @return 是否点赞
     */
    private boolean isLiked(Integer userId, String noteId) {
        try {
            String userKey = String.format(USER_LIKE_KEY, userId);
            String targetKey = "note:" + noteId;
            return cacheService.hExists(userKey, targetKey);
        } catch (Exception e) {
            log.warn("判断点赞状态失败, userId: {}, noteId: {}", userId, noteId, e);
            return false;
        }
    }

    /**
     * 判断用户是否收藏
     *
     * @param userId 用户ID
     * @param noteId 笔记ID
     * @return 是否收藏
     */
    private boolean isCollected(Integer userId, String noteId) {
        try {
            String userKey = String.format(USER_COLLECT_KEY, userId);
            String targetKey = "note:" + noteId;
            return cacheService.hExists(userKey, targetKey);
        } catch (Exception e) {
            log.warn("判断收藏状态失败, userId: {}, noteId: {}", userId, noteId, e);
            return false;
        }
    }

    /**
     * 设置默认统计数据
     *
     * @param note 笔记对象
     */
    private void setDefaultStatistics(Note note) {
        if (note != null) {
            note.setLikeCount(0);
            note.setCollectCount(0);
            note.setCommentCount(0);
            note.setShareCount(0);
            note.setIsLiked(false);
            note.setIsCollected(false);
        }
    }
}
